﻿using System;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using jmail;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Xml;
using System.Security.Cryptography;


/// <summary>
/// functions 的摘要说明
/// </summary>
public class functions
{
	public functions()
	{
		//
		// TODO: 在此处添加构造函数逻辑
		//
	}
    /// <summary>
    /// 获得最底层Exception
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public static Exception GetTheBaseException(Exception e)
    {
        if (e.InnerException == null)
        {
            return e;
        }
        else
        {
            return GetTheBaseException(e.InnerException);
        }
    }
    //转化Sql语句的函数,防止SQL注入
    public static string chgSql(string strSql)
    {
        strSql = strSql + "";
        strSql = strSql.Replace("'", "''");

        return strSql;
    }
    public static string chgSql_news(string strSql)
    {
        strSql = (strSql + "").Trim();
        strSql = strSql.Replace("'", "''");
        return strSql;
    }
    /// <summary>
    /// HTML转换
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    static public string ToChgHTMLString(string input)
    {
        if (input == null) return "";
        input = input.Replace("&lt;", "<");
        input = input.Replace("&gt;", ">");
        input = input.Replace("&amp;", "&");
        input = input.Replace("&quot;", "\"");
        input = input.Replace("&copy;", "©");
        input = input.Replace("&reg;", "®");
        input = input.Replace("&yen;", "￥");
        input = input.Replace("&nbsp;", " ");
        input = input.Replace("\r\n", "<br>");
        return input;
    }
    //截取字符限制长度
    public static string limitLength(string value1, int intLength)
    {
        int intLgth1;
        value1 = value1 + "";
        if (intLength != 0)
        {
            intLgth1 = value1.Length;
            if (intLgth1 > intLength)
            {
                value1 = value1.Substring(0, intLength);
            }

        }
        return value1;
    }
    //插入语句的信息
    public static string chgInsertStrValues(string value1, int intLength, string values)
    {
        int intLgth1;

        values = values + "";

        value1 = limitLength(value1, intLength);

        if (intLength != 0)
        {
            intLgth1 = value1.Length;
            if (intLgth1 > intLength)
            {
                value1 = value1.Substring(0, intLength);
            }
        }

        if (values == "")
        {
            values = "'" + chgSql(value1) + "'";
        }
        else
        {
            values = values + ",'" + chgSql(value1) + "'";
        }
        return values;
    }
    //更新语句的信息
    public static string chgUpdateStrValues(string value1, string strField, int intLength, string values)
    {
        int intLgth1;
        values = values + "";
        value1 = limitLength(value1, intLength);

        if (intLength != 0)
        {
            intLgth1 = value1.Length;
            if (intLgth1 > intLength)
            {
                value1 = value1.Substring(0, intLength);
            }
        }

        if (values == "")
        {
            values = strField + "='" + chgSql(value1) + "'";
        }
        else
        {
            values = values + "," + strField + "='" + chgSql(value1) + "'";
        }
        return values;
    }
    /// <summary>
    /// 获取汉字首字母
    /// </summary>
    /// <param name="chrstr"></param>
    /// <returns></returns>
    public static string convertToWord(string chrstr)
    {
        int[] pyvalue = new int[] { -20319, -20317, -20304, -20295, -20292, -20283, -20265, -20257, -20242, -20230, -20051, -20036, -20032, -20026, -20002, -19990, -19986, -19982, -19976, -19805, -19784, -19775, -19774, -19763, -19756, -19751, -19746, -19741, -19739, -19728, -19725, -19715, -19540, -19531, -19525, -19515, -19500, -19484, -19479, -19467, -19289, -19288, -19281, -19275, -19270, -19263, -19261, -19249, -19243, -19242, -19238, -19235, -19227, -19224, -19218, -19212, -19038, -19023, -19018, -19006, -19003, -18996, -18977, -18961, -18952, -18783, -18774, -18773, -18763, -18756, -18741, -18735, -18731, -18722, -18710, -18697, -18696, -18526, -18518, -18501, -18490, -18478, -18463, -18448, -18447, -18446, -18239, -18237, -18231, -18220, -18211, -18201, -18184, -18183, -18181, -18012, -17997, -17988, -17970, -17964, -17961, -17950, -17947, -17931, -17928, -17922, -17759, -17752, -17733, -17730, -17721, -17703, -17701, -17697, -17692, -17683, -17676, -17496, -17487, -17482, -17468, -17454, -17433, -17427, -17417, -17202, -17185, -16983, -16970, -16942, -16915, -16733, -16708, -16706, -16689, -16664, -16657, -16647, -16474, -16470, -16465, -16459, -16452, -16448, -16433, -16429, -16427, -16423, -16419, -16412, -16407, -16403, -16401, -16393, -16220, -16216, -16212, -16205, -16202, -16187, -16180, -16171, -16169, -16158, -16155, -15959, -15958, -15944, -15933, -15920, -15915, -15903, -15889, -15878, -15707, -15701, -15681, -15667, -15661, -15659, -15652, -15640, -15631, -15625, -15454, -15448, -15436, -15435, -15419, -15416, -15408, -15394, -15385, -15377, -15375, -15369, -15363, -15362, -15183, -15180, -15165, -15158, -15153, -15150, -15149, -15144, -15143, -15141, -15140, -15139, -15128, -15121, -15119, -15117, -15110, -15109, -14941, -14937, -14933, -14930, -14929, -14928, -14926, -14922, -14921, -14914, -14908, -14902, -14894, -14889, -14882, -14873, -14871, -14857, -14678, -14674, -14670, -14668, -14663, -14654, -14645, -14630, -14594, -14429, -14407, -14399, -14384, -14379, -14368, -14355, -14353, -14345, -14170, -14159, -14151, -14149, -14145, -14140, -14137, -14135, -14125, -14123, -14122, -14112, -14109, -14099, -14097, -14094, -14092, -14090, -14087, -14083, -13917, -13914, -13910, -13907, -13906, -13905, -13896, -13894, -13878, -13870, -13859, -13847, -13831, -13658, -13611, -13601, -13406, -13404, -13400, -13398, -13395, -13391, -13387, -13383, -13367, -13359, -13356, -13343, -13340, -13329, -13326, -13318, -13147, -13138, -13120, -13107, -13096, -13095, -13091, -13076, -13068, -13063, -13060, -12888, -12875, -12871, -12860, -12858, -12852, -12849, -12838, -12831, -12829, -12812, -12802, -12607, -12597, -12594, -12585, -12556, -12359, -12346, -12320, -12300, -12120, -12099, -12089, -12074, -12067, -12058, -12039, -11867, -11861, -11847, -11831, -11798, -11781, -11604, -11589, -11536, -11358, -11340, -11339, -11324, -11303, -11097, -11077, -11067, -11055, -11052, -11045, -11041, -11038, -11024, -11020, -11019, -11018, -11014, -10838, -10832, -10815, -10800, -10790, -10780, -10764, -10587, -10544, -10533, -10519, -10331, -10329, -10328, -10322, -10315, -10309, -10307, -10296, -10281, -10274, -10270, -10262, -10260, -10256, -10254 };
        string[] pystr = new string[] { "a", "ai", "an", "ang", "ao", "ba", "bai", "ban", "bang", "bao", "bei", "ben", "beng", "bi", "bian", "biao", "bie", "bin", "bing", "bo", "bu", "ca", "cai", "can", "cang", "cao", "ce", "ceng", "cha", "chai", "chan", "chang", "chao", "che", "chen", "cheng", "chi", "chong", "chou", "chu", "chuai", "chuan", "chuang", "chui", "chun", "chuo", "ci", "cong", "cou", "cu", "cuan", "cui", "cun", "cuo", "da", "dai", "dan", "dang", "dao", "de", "deng", "di", "dian", "diao", "die", "ding", "diu", "dong", "dou", "du", "duan", "dui", "dun", "duo", "e", "en", "er", "fa", "fan", "fang", "fei", "fen", "feng", "fo", "fou", "fu", "ga", "gai", "gan", "gang", "gao", "ge", "gei", "gen", "geng", "gong", "gou", "gu", "gua", "guai", "guan", "guang", "gui", "gun", "guo", "ha", "hai", "han", "hang", "hao", "he", "hei", "hen", "heng", "hong", "hou", "hu", "hua", "huai", "huan", "huang", "hui", "hun", "huo", "ji", "jia", "jian", "jiang", "jiao", "jie", "jin", "jing", "jiong", "jiu", "ju", "juan", "jue", "jun", "ka", "kai", "kan", "kang", "kao", "ke", "ken", "keng", "kong", "kou", "ku", "kua", "kuai", "kuan", "kuang", "kui", "kun", "kuo", "la", "lai", "lan", "lang", "lao", "le", "lei", "leng", "li", "lia", "lian", "liang", "liao", "lie", "lin", "ling", "liu", "long", "lou", "lu", "lv", "luan", "lue", "lun", "luo", "ma", "mai", "man", "mang", "mao", "me", "mei", "men", "meng", "mi", "mian", "miao", "mie", "min", "ming", "miu", "mo", "mou", "mu", "na", "nai", "nan", "nang", "nao", "ne", "nei", "nen", "neng", "ni", "nian", "niang", "niao", "nie", "nin", "ning", "niu", "nong", "nu", "nv", "nuan", "nue", "nuo", "o", "ou", "pa", "pai", "pan", "pang", "pao", "pei", "pen", "peng", "pi", "pian", "piao", "pie", "pin", "ping", "po", "pu", "qi", "qia", "qian", "qiang", "qiao", "qie", "qin", "qing", "qiong", "qiu", "qu", "quan", "que", "qun", "ran", "rang", "rao", "re", "ren", "reng", "ri", "rong", "rou", "ru", "ruan", "rui", "run", "ruo", "sa", "sai", "san", "sang", "sao", "se", "sen", "seng", "sha", "shai", "shan", "shang", "shao", "she", "shen", "sheng", "shi", "shou", "shu", "shua", "shuai", "shuan", "shuang", "shui", "shun", "shuo", "si", "song", "sou", "su", "suan", "sui", "sun", "suo", "ta", "tai", "tan", "tang", "tao", "te", "teng", "ti", "tian", "tiao", "tie", "ting", "tong", "tou", "tu", "tuan", "tui", "tun", "tuo", "wa", "wai", "wan", "wang", "wei", "wen", "weng", "wo", "wu", "xi", "xia", "xian", "xiang", "xiao", "xie", "xin", "xing", "xiong", "xiu", "xu", "xuan", "xue", "xun", "ya", "yan", "yang", "yao", "ye", "yi", "yin", "ying", "yo", "yong", "you", "yu", "yuan", "yue", "yun", "za", "zai", "zan", "zang", "zao", "ze", "zei", "zen", "zeng", "zha", "zhai", "zhan", "zhang", "zhao", "zhe", "zhen", "zheng", "zhi", "zhong", "zhou", "zhu", "zhua", "zhuai", "zhuan", "zhuang", "zhui", "zhun", "zhuo", "zi", "zong", "zou", "zu", "zuan", "zui", "zun", "zuo" };
        byte[] array = new byte[2];
        string returnstr = "";
        int chrasc = 0;
        int i1 = 0;
        int i2 = 0;

        char[] nowchar = chrstr.ToCharArray();
        for (int j = 0; j < nowchar.Length; j++)
        {

            array = System.Text.Encoding.Default.GetBytes(nowchar[j].ToString());
            if (array.Length < 2)
            {
                returnstr += nowchar[j];
                continue;
            }
            i1 = (short)(array[0]);
            i2 = (short)(array[1]);

            chrasc = i1 * 256 + i2 - 65536;
            if (chrasc > 0 && chrasc < 160)
            {
                returnstr += nowchar[j];
            }
            else
            {
                for (int i = (pyvalue.Length - 1); i >= 0; i--)
                {
                    if (pyvalue[i] <= chrasc)
                    {
                        returnstr += pystr[i].Substring(0, 1);
                        break;
                    }
                }
            }
        }
        return returnstr.ToUpper();

    }
    //数据读入textbox的转化
    public static string chgInput(string strInput)
    {
        string strValue = strInput + "";
        strValue = strValue.Replace("'", "&#39;");
        strValue = strValue.Replace("<", "&#60;");
        strValue = strValue.Replace(">", "&#62;");
        strValue = strValue.Replace("\"", "&#34;");
        return strValue;
    }
    //按字节截取字符串
    public static string GetFirstString(string stringToSub, int length)
    {
        Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
        char[] stringChar = stringToSub.ToCharArray();
        StringBuilder sb = new StringBuilder();
        int nLength = 0;
        for (int i = 0; i < stringChar.Length; i++)
        {
            if (regex.IsMatch((stringChar[i]).ToString()))
            {
                nLength += 2;
            }
            else
            {
                nLength = nLength + 1;
            }

            if (nLength <= length)
            {
                sb.Append(stringChar[i]);
            }
            else
            {
                break;
            }
        }
        if (sb.ToString() != stringToSub)
        {
            sb.Append("...");
        }
        return sb.ToString();
    }
    public static int GetStringCharCount(string stringToSub)
    {
        Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
        char[] stringChar = stringToSub.ToCharArray();
        StringBuilder sb = new StringBuilder();
        int nLength = 0;
        for (int i = 0; i < stringChar.Length; i++)
        {
            if (regex.IsMatch((stringChar[i]).ToString()))
            {
                nLength += 2;
            }
            else
            {
                nLength = nLength + 1;
            }
        }
        return nLength;
    }

    //判断是不是整数
    public static bool IsInteger(string str)
    {
        if (str == null || str.Length == 0)
        {
            return false;
        }
        System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();

        byte[] bytestr = ascii.GetBytes(str);

        foreach (byte c in bytestr)
        {
            if (c < 48 || c > 57)
            {
                return false;
            }
        }
        return true;
    }

    //判断是不是数字
    public static bool isnumber(string str)
    {
        try
        {
            double s = 0;
            s = Convert.ToDouble(str);
            return true;
        }
        catch
        {
            return false;
        }

    }

    public static int intWeekDay(int y, int m, int d)
    {
        //计算今天是星期几 1表示周一 2周二....7表示周日
        if (m == 1)
        {
            m = 13;
            y = y - 1;
        }
        if (m == 2)
        {
            m = 14;
            y = y - 1;
        }
        int week = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7;
        week = week + 1;
        return week;
    }

    //计算今天是哪个季度,06Q3、07Q2...
    public static string season()
    {
        string year = System.DateTime.Now.Year.ToString().Substring(2, 2);
        string season = "";
        int month = System.DateTime.Now.Month;
        if (month % 3 == 0)
        {
            season = "Q" + (month / 3);
        }
        else
        {
            season = "Q" + (Convert.ToInt32(month / 3) + 1);
        }
        return year + season;
    }
    public static string season(string date)
    {
        string year = date.Substring(2, 2);
        string season = "";
        int month = Convert.ToDateTime(date).Month;
        if (month % 3 == 0)
        {
            season = "Q" + (month / 3);
        }
        else
        {
            season = "Q" + (Convert.ToInt32(month / 3) + 1);
        }
        return year + season;
    }

    public static string HTMLEncode(string fString)
    {
        if (fString != string.Empty)
        {
            ///替换尖括号
            fString = fString.Replace("<", "&lt;");
            fString = fString.Replace(">", "&gt;");
            ///替换引号
            fString = fString.Replace(((char)34).ToString(), "&quot;");
            fString = fString.Replace(((char)39).ToString(), "&#39;");
            ///替换空格
            fString = fString.Replace(((char)13).ToString(), "");
            ///替换换行符
            fString = fString.Replace(((char)10).ToString(), "<BR> ");
        }
        return (fString);
    }

    public static string Letter(int number)
    {
        switch (number)
        {
            case 1:
                return "A";
            case 2:
                return "B";
            case 3:
                return "C";
            case 4:
                return "D";
            case 5:
                return "E";
            case 6:
                return "F";
            case 7:
                return "G";
            case 8:
                return "H";
            case 9:
                return "I";
            case 10:
                return "J";
            case 11:
                return "K";
            case 12:
                return "L";
            case 13:
                return "M";
            case 14:
                return "N";
            case 15:
                return "O";
            case 16:
                return "P";
            case 17:
                return "Q";
            case 18:
                return "R";
            case 19:
                return "S";
            case 20:
                return "T";
            case 21:
                return "U";
            case 22:
                return "V";
            case 23:
                return "W";
            case 24:
                return "X";
            case 25:
                return "Y";
            case 26:
                return "Z";
            default:
                return "0";
        }
    }


    /// <summary>
    /// Jmail发邮件
    /// </summary>
    /// <param name="toEmail">接收者（多位用分号隔开）</param>
    /// <param name="toCCMail">抄送（多位用分号隔开）</param>
    /// <param name="toBCCMail">密送（多位用分号隔开）</param>
    /// <param name="FromEmail">发件者</param>
    /// <param name="strToName">收件人姓名</param>
    /// <param name="strFromName">发件人姓名</param>
    /// <param name="strContent">邮件内容</param>
    /// <param name="strTitle">邮件标题</param>
    /// <param name="strContentType">邮件类别（html或者text）</param>
    /// <param name="strFiles">附件（多个用分号隔开）</param>
    /// <returns></returns>
    public static bool SendEmail2(string toEmail, string toBCCMail, string toCCMail, string FromEmail, string strToName, string strFromName, string strContent, string strTitle, string strContentType, string strFiles)
    {

        jmail.Message Jmail = new jmail.Message();
        int i = 0;

        string username = System.Configuration.ConfigurationManager.AppSettings["mailusername"].ToString();
        string password = System.Configuration.ConfigurationManager.AppSettings["mailpassword"].ToString();
        string mailhost = System.Configuration.ConfigurationManager.AppSettings["mailSmtpHost"].ToString();
        string mailfrom = System.Configuration.ConfigurationManager.AppSettings["mailusername"].ToString();

        if (strTitle != "ERROR Message") toBCCMail = "cherry.zhao@micromarketing.com.cn;shiwei.wang@micromarketing.com.cn;heidi.zhu@micromarketing.com.cn";

        string ccid01;

        if (System.Configuration.ConfigurationManager.AppSettings["constr"] + "" == "Data Source=10.10.10.10;UID=sa;PWD=mm17sql;DATABASE=AMD_XLH_Test" || System.Configuration.ConfigurationManager.AppSettings["constr"] + "" == "Data Source=10.10.10.10;UID=sa;PWD=mm17sql;DATABASE=AMD_XLH")
        {
            ccid01 = Jmail.AddURLAttachment("http://10.10.10.10/AMD_XLH/images/index/logo_mail.jpg", "logo_mail.jpg", true, "");
        }
        else
        {
            ccid01 = Jmail.AddURLAttachment("http://211.103.152.10/AMD_XLH/images/index/logo_mail.jpg", "logo_mail.jpg", true, "");
        }

        strContent = "<html xmlns=\"http://www.w3.org/1999/xhtml\">"
                        + "<head>"
                        + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\" />"
                        + "<title></title>"
                        + "<style type=\"text/css\">"
                        + ".bt {"
                        + "	font-family: \"Arial\", \"Helvetica\", \"sans-serif\";"
                        + "	font-size: 9pt;"
                        + "	line-height: normal;"
                        + "	color: #000000;"
                        + "</style>"
                        + "</head>"
                        + "<body >"
                        + "<div class=\"bt\">"
                        + strContent
                        + "<br /><br/>"
                        + "<a href=\"http://www.amdxlh.com.cn\" target=\"_blank\"><img src=\"cid:" + ccid01 + "\" border=0></a><br />"
                        + "热线电话：010-8586 2323 - 860 <br />"
                        + "反馈邮箱：<a href=\"mailto:amdxlh@micromarketing.com.cn\">amdxlh@micromarketing.com.cn</a><br />"
                        + "</div>"
                        + "</body>"
                        + "</html>";

        string issendemail = System.Configuration.ConfigurationManager.AppSettings["issendemail"];
        if (issendemail == "false" && strTitle != "ERROR Message")
        {
            toEmail = "cherry.zhao@micromarketing.com.cn";
            toCCMail = System.Configuration.ConfigurationManager.AppSettings["testbccmail"] + "";
            toBCCMail = "";
        }
        try
        {
            //Silent属性：如果设置为true,JMail不会抛出例外错误. JMail. Send( () 会根据操作结果返回true或false
            Jmail.Silent = true;
            //Jmail创建的日志，前提loging属性设置为true
            Jmail.Logging = true;
            //字符集，缺省为"US-ASCII"
            Jmail.Charset = "GB2312";
            //信件的contentype. 缺省是"text/plain"） : 字符串如果你以HTML格式发送邮件, 改为"text/html"即可。
            //Jmail.ContentType = "Multipart/Mixed";
            //添加收件人
            string[] strArryToMail;
            string[] strArryToCCMail;
            string[] strArryToBCCMail;
            if (toEmail == "")
            {
                Jmail.Close();
                return false;
            }
            else
            {
                strArryToMail = toEmail.Split(";".ToCharArray());
            }
            for (i = 0; i < strArryToMail.Length; i++)
            {
                Jmail.AddRecipient(strArryToMail[i], "", "");
            }

            //Jmail.add
            //抄送
            if (toCCMail != "")
            {
                strArryToCCMail = toCCMail.Split(";".ToCharArray());
                for (i = 0; i < strArryToCCMail.Length; i++)
                {
                    Jmail.AddRecipientCC(strArryToCCMail[i], "", "");
                }
            }
            //密送
            if (toBCCMail != "")
            {
                strArryToBCCMail = toBCCMail.Split(";".ToCharArray());
                for (i = 0; i < strArryToBCCMail.Length; i++)
                {
                    Jmail.AddRecipientBCC(strArryToBCCMail[i], "");
                }
            }

            Jmail.From = mailfrom;
            Jmail.FromName = strFromName;
            //发件人邮件用户名
            Jmail.MailServerUserName = username;
            //发件人邮件密码
            Jmail.MailServerPassWord = password;
            //设置邮件标题
            Jmail.Subject = strTitle;
            //邮件添加附件,(多附件的话，可以再加一条Jmail.AddAttachment( "c:\\test.jpg",true,null);)就可以搞定了。［注］：加了附件，讲把上面的Jmail.ContentType="text/html";删掉。否则会在邮件里出现乱码。
            string[] strArryFiles;
            if (strFiles != "")
            {
                strArryFiles = strFiles.Split(";".ToCharArray());
                for (i = 0; i < strArryFiles.Length; i++)
                {
                    Jmail.AddAttachment(strArryFiles[i], true, null);
                }
            }
            //邮件内容
            if (strContentType.ToLower() == "text")
            {
                Jmail.Body = strContent;

            }
            else
            {
                Jmail.HTMLBody = strContent;
            }
            //Jmail发送的方法
            if (Jmail.Send(mailhost, false))
            {
                //
                Jmail.Close();
                return true;
            }
            else
            {
                //
                Logs.WebLogs Logs = new Logs.WebLogs();
                Logs.Add("sendemailerror", "", "", "tomail:" + toEmail + "content:" + strContent, "", "", "", "");
                Jmail.Close();
                return false;
            }

        }
        catch (Exception ex)
        {
            DataClass.WriteLog(ex, "邮件发送异常");
            Jmail.Close();
            return false;
        }
    }
    /// <summary>
    /// 生成缩略图
    /// </summary>
    /// <param name="originalImagePath">源图路径（物理路径）</param>
    /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
    /// <param name="width">缩略图宽度</param>
    /// <param name="height">缩略图高度</param>
    /// <param name="mode">生成缩略图的方式</param> 
    public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
    {
        System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

        int towidth;
        int toheight;
        if (((double)originalImage.Width <= 640 && (double)originalImage.Height <= 480) || ((double)originalImage.Width <= 480 && (double)originalImage.Height <= 640)) //图片比640*480小就不裁减
        {
            towidth = (int)originalImage.Width;
            toheight = (int)originalImage.Height;
        }
        else
        {
            if ((double)originalImage.Width / (double)originalImage.Height >= 1)
            {
                towidth = 640;
                toheight = (int)((double)originalImage.Height * (640 / (double)originalImage.Width));
            }
            else
            {
                toheight = 640;
                towidth = (int)((double)originalImage.Width * (640 / (double)originalImage.Height));
            }
        }




        int x = 0;
        int y = 0;
        int ow = originalImage.Width;
        int oh = originalImage.Height;

        switch (mode)
        {
            case "HW": //指定高宽缩放（可能变形） 
                break;
            case "W": //指定宽，高按比例 
                toheight = originalImage.Height * width / originalImage.Width;
                break;
            case "H": //指定高，宽按比例
                towidth = originalImage.Width * height / originalImage.Height;
                break;
            case "Cut": //指定高宽裁减（不变形） 
                if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * towidth / toheight;
                    y = 0;
                    x = (originalImage.Width - ow) / 2;
                }
                else
                {
                    if ((double)originalImage.Width / (double)originalImage.Height == (double)towidth / (double)toheight)
                    {
                        x = 0;
                        y = 0;
                        ow = originalImage.Width;
                        oh = originalImage.Height;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                }
                break;
            default:
                break;
        }

        //新建一个bmp图片
        System.Drawing.Image bitmap = new Bitmap(towidth, toheight);

        //新建一个画板
        Graphics g = Graphics.FromImage(bitmap);

        //设置高质量插值法
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        //设置高质量,低速度呈现平滑程度
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        //清空画布并以透明背景色填充
        g.Clear(Color.Transparent);

        //在指定位置并且按指定大小绘制原图片的指定部分
        g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
        new Rectangle(x, y, ow, oh),
        GraphicsUnit.Pixel);

        try
        {
            //以jpg格式保存缩略图
            bitmap.Save(thumbnailPath, ImageFormat.Jpeg);

        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            originalImage.Dispose();
            bitmap.Dispose();
            g.Dispose();
            File.Delete(originalImagePath);
        }
    }

    public static void MakeThumbnailA(string originalImagePath, string thumbnailPath, int width, int height, string mode)
    {
        System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

        int towidth;
        int toheight;

        towidth = width;
        toheight = height;


        int x = 0;
        int y = 0;
        int ow = originalImage.Width;
        int oh = originalImage.Height;

        switch (mode)
        {
            case "HW": //指定高宽缩放（可能变形） 
                break;
            case "W": //指定宽，高按比例 
                toheight = originalImage.Height * width / originalImage.Width;
                break;
            case "H": //指定高，宽按比例
                towidth = originalImage.Width * height / originalImage.Height;
                break;
            case "Cut": //指定高宽裁减（不变形） 
                if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * towidth / toheight;
                    y = 0;
                    x = (originalImage.Width - ow) / 2;
                }
                else
                {
                    if ((double)originalImage.Width / (double)originalImage.Height == (double)towidth / (double)toheight)
                    {
                        x = 0;
                        y = 0;
                        ow = originalImage.Width;
                        oh = originalImage.Height;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                }
                break;
            default:
                break;
        }

        //新建一个bmp图片
        System.Drawing.Image bitmap = new Bitmap(towidth, toheight);

        //新建一个画板
        Graphics g = Graphics.FromImage(bitmap);

        //设置高质量插值法
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        //设置高质量,低速度呈现平滑程度
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        //清空画布并以透明背景色填充
        g.Clear(Color.Transparent);

        //在指定位置并且按指定大小绘制原图片的指定部分
        g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
        new Rectangle(x, y, ow, oh),
        GraphicsUnit.Pixel);

        try
        {
            //以jpg格式保存缩略图
            bitmap.Save(thumbnailPath, ImageFormat.Jpeg);

        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            originalImage.Dispose();
            bitmap.Dispose();
            g.Dispose();
            File.Delete(originalImagePath);
        }
    }


    #region 先得到上传Xls文件在服务器上的绝对路径,然后得到服务器上的Xls填充的DataTable
    /// <summary>
    /// 先得到上传Xls文件在服务器上的绝对路径,然后得到服务器上的Xls填充的DataTable
    /// </summary>
    /// <param name="fuXls">上传控件</param>
    /// <param name="folderName">上传到的文件夹在服务器上的绝对路径</param>
    /// <param name="fields">要读取的字段，以,分割，至少要有一个字段</param>
    /// <returns>DataTable，为null读取失败</returns>
    public static DataTable getUploadData(FileUpload fuXls, string folderName, string fields, ref string cueInfo)
    {
        DataTable dtSell = null;
        //得到上传Xls文件在服务器上的绝对路径,为空("")上传失败  
        string path = getUploadFilePath(fuXls, folderName, ref cueInfo);
        if (!String.IsNullOrEmpty(path))
        {
            //得到服务器上的Xls填充的DataTable
            dtSell = getDataTableSell(path, fields, ref cueInfo);
        }

        return dtSell;
    }
    #endregion


    #region 得到上传Xls文件在服务器上的绝对路径
    /// <summary>
    ///  得到上传Xls文件在服务器上的绝对路径,为空("")上传失败  
    /// </summary>
    /// <param name="fuXls">上传控件</param>
    /// <param name="folderName">上传到的文件夹在服务器上的绝对路径</param>
    /// <returns>上传到服务器上的路径，为空("")上传失败</returns>
    public static string getUploadFilePath(FileUpload fuXls, string folderName, ref string cueInfo)
    {
        string path = "";
        if (fuXls.HasFile)
        {
            //取得文件扩展名
            string extension = System.IO.Path.GetExtension(fuXls.FileName);
            if (extension.ToLower() == ".xls")
            {
                ////得到服务器根目录
                //string serverPath = Server.MapPath("."); System
                ////得到绝对路径(注意: 在asp.net里"\"必须用"\\"代替)
                //path = serverPath + "\\Sells\\" + folderName + "\\" + System.Guid.NewGuid().ToString() + ".xls";
                path = folderName + "\\" + System.Guid.NewGuid().ToString() + ".xls";
                //保存文件到服务器
                try
                {
                    fuXls.PostedFile.SaveAs(path);
                }
                catch
                {
                    //保存出错
                    path = "";
                    cueInfo += "保存到服务器失败!!<br />";
                }
            }
            else
            {
                cueInfo += "请上传Excel文件!!<br />";
            }
        }
        else
        {
            cueInfo += "请选择要上传的Excel文件!!<br />";
        }
        return path;
    }
    #endregion


    #region 得到服务器上的Xls填充的DataTable
    /// <summary>
    /// 得到服务器上的Xls填充的DataTable
    /// </summary>
    /// <param name="path">xls在服务器上的绝对路径</param>
    /// <param name="fields">要读取的字段，以,分割，至少要有一个字段</param>
    /// <returns>DataTable，为null读取失败</returns>
    private static DataTable getDataTableSell(string path, string fields, ref string cueInfo)
    {
        string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Extended Properties=Excel 8.0;" + "data source=" + path;
        DataTable dtSell = null;
        try
        {
            DataSet dsSell = new DataSet();
            using (OleDbConnection odconn = new OleDbConnection(connStr))
            {
                using (OleDbDataAdapter odda = new OleDbDataAdapter(@"SELECT " + fields + " FROM [Sheet1$]", odconn))
                {
                    odda.Fill(dsSell, "sell");
                    if (dsSell != null && dsSell.Tables.Count > 0)
                    {
                        dtSell = dsSell.Tables[0];
                    }
                }
            }
        }
        catch
        {
            cueInfo += "从Excel读取数据失败!!<br />";
        }
        return dtSell;
    }
    #endregion

    public static string GetContentSummary(string content, int length, bool StripHTML)
    {
        if (string.IsNullOrEmpty(content) || length == 0)
            return "";
        if (StripHTML)
        {
            System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex("<[^>]*>");
            content = re.Replace(content, "");
            content = content.Replace("　", "").Replace(" ", "").Replace("&nbsp;", "");
            if (content.Length <= length)
                return content;
            else
                return content.Substring(0, length) + "...";
        }
        else
        {
            if (content.Length <= length)
                return content;

            int pos = 0, npos = 0, size = 0;
            bool firststop = false, notr = false, noli = false;
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            while (true)
            {
                if (pos >= content.Length)
                    break;
                string cur = content.Substring(pos, 1);
                if (cur == "<")
                {
                    string next = content.Substring(pos + 1, 3).ToLower();
                    if (next.IndexOf("p") == 0 && next.IndexOf("pre") != 0)
                    {
                        npos = content.IndexOf(">", pos) + 1;
                    }
                    else if (next.IndexOf("/p") == 0 && next.IndexOf("/pr") != 0)
                    {
                        npos = content.IndexOf(">", pos) + 1;
                        if (size < length)
                            sb.Append("<br />");
                    }
                    else if (next.IndexOf("br") == 0)
                    {
                        npos = content.IndexOf(">", pos) + 1;
                        if (size < length)
                            sb.Append("<br />");
                    }
                    else if (next.IndexOf("img") == 0)
                    {
                        npos = content.IndexOf(">", pos) + 1;
                        if (size < length)
                        {
                            sb.Append(content.Substring(pos, npos - pos));
                            size += npos - pos + 1;
                        }
                    }
                    else if (next.IndexOf("li") == 0 || next.IndexOf("/li") == 0)
                    {
                        npos = content.IndexOf(">", pos) + 1;
                        if (size < length)
                        {
                            sb.Append(content.Substring(pos, npos - pos));
                        }
                        else
                        {
                            if (!noli && next.IndexOf("/li") == 0)
                            {
                                sb.Append(content.Substring(pos, npos - pos));
                                noli = true;
                            }
                        }
                    }
                    else if (next.IndexOf("tr") == 0 || next.IndexOf("/tr") == 0)
                    {
                        npos = content.IndexOf(">", pos) + 1;
                        if (size < length)
                        {
                            sb.Append(content.Substring(pos, npos - pos));
                        }
                        else
                        {
                            if (!notr && next.IndexOf("/tr") == 0)
                            {
                                sb.Append(content.Substring(pos, npos - pos));
                                notr = true;
                            }
                        }
                    }
                    else if (next.IndexOf("td") == 0 || next.IndexOf("/td") == 0)
                    {
                        npos = content.IndexOf(">", pos) + 1;
                        if (size < length)
                        {
                            sb.Append(content.Substring(pos, npos - pos));
                        }
                        else
                        {
                            if (!notr)
                            {
                                sb.Append(content.Substring(pos, npos - pos));
                            }
                        }
                    }
                    else
                    {
                        npos = content.IndexOf(">", pos) + 1;
                        sb.Append(content.Substring(pos, npos - pos));
                    }
                    if (npos <= pos)
                        npos = pos + 1;
                    pos = npos;
                }
                else
                {
                    if (size < length)
                    {
                        sb.Append(cur);
                        size++;
                    }
                    else
                    {
                        if (!firststop)
                        {
                            sb.Append("...");
                            firststop = true;
                        }
                    }
                    pos++;
                }

            }
            return sb.ToString();
        }
    }

    #region MD5　
    //md5加密算法
    public static string GetMd5Str(string ConvertString)
    {
        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
        string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
        t2 = t2.Replace("-", "");
        return t2;
    }
    #endregion

    #region MD5　32位加密
    /// <summary> 
    /// MD5　32位加密 
    /// </summary> 
    /// <param name="str"></param> 
    /// <returns></returns> 
    public static string UserMd5(string str)
    {
        string cl = str;
        string pwd = "";
        MD5 md5 = MD5.Create();//实例化一个md5对像 
        // 加密后是一个字节类型的数组，这里要注意编码UTF8/Unicode等的选择　 
        byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
        // 通过使用循环，将字节类型的数组转换为字符串，此字符串是常规字符格式化所得 
        for (int i = 0; i < s.Length; i++)
        {
            // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符 

            pwd = pwd + s[i].ToString("X");

        }
        return pwd;
    }
    #endregion

    #region AMDSchool用的密码加密方法

    /// <summary>
    /// 对输入密码文字进行MD5 加密
    /// </summary>
    /// <param name="sourceText">输入密码文字</param>
    /// <returns>加密后的密码文字</returns>
    public static string ComputeHash(string sourceText)
    {
        if (sourceText == null)
            return null;

        MD5CryptoServiceProvider md5Service = new MD5CryptoServiceProvider();

        System.Text.UTF8Encoding encoder = new UTF8Encoding();
        byte[] encodeBytes = encoder.GetBytes(sourceText);
        byte[] hashedBytes = md5Service.ComputeHash(encodeBytes);
        md5Service.Clear();

        return System.Convert.ToBase64String(hashedBytes);
    }

    #endregion

    #region 解密
    public static string UrlPro(string para, string url)
    {
        string[] splitChar = new string[2];
        splitChar[0] = "?" + para + "=";
        splitChar[1] = "&" + para + "=";

        string id = "0";

        int index = 0;
        int i = 0;
        for (i = 0; i < splitChar.Length; i++)
        {
            index = url.IndexOf(splitChar[i]);
            if (index != -1)
            {
                break;
            }
        }

        if (index == -1)
        {
            id = "0";
        }
        else
        {
            id = url.Substring(index + splitChar[i].Length, url.Length - index - splitChar[i].Length);

            // 进行解密

            try
            {
                SymmetricMethod sm = new SymmetricMethod();

                id = Convert.ToString(sm.Decrypto(id));
            }
            catch
            {
                //Response.Write("<script>alert('解析地址时出错!!');window.location.href='"+tourl+"';</script>");
                return "0";
            }
        }

        return id;
    }
    #endregion

    #region 加密
    public static string IDEncrypto(string id)
    {
        SymmetricMethod sm = new SymmetricMethod();
        string strID = sm.Encrypto(id);

        return strID;

    }
    #endregion

    #region 生成XML节点
    public static XmlElement GetXmlElement(XmlDocument xmlDocument, string element, string textNode)
    {
        XmlElement xmlElement = xmlDocument.CreateElement(element);
        XmlText xmlText = xmlDocument.CreateTextNode(textNode);
        xmlElement.AppendChild(xmlText);
        return xmlElement;
    }
    #endregion

    /// <summary>
    /// 获取当前请求的IP地址
    /// </summary>
    /// <returns>IP地址</returns>
    public static string GetIPAddress()
    {
        string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (string.IsNullOrEmpty(ip))
        {
            ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }
        if (string.IsNullOrEmpty(ip))
        {
            ip = HttpContext.Current.Request.UserHostAddress;
        }
        return ip;
    }

    //,防止XSS
    public static string chgXSS(string str)
    {

        str = (str + "").Trim();
        if (str.ToLower().Contains("&lt;script") || str.ToLower().Contains("&lt;/script&gt;"))
        {
            str = str.Replace("&lt;script", "&lt;p&gt;&amp;lt;script");
            str = str.Replace("&lt;/script&gt;", "&amp;lt;/script&amp;gt;&lt;/p&gt;");
        }
        str = str.Replace("<", "&#60;");
        str = str.Replace(">", "&#62;");
        str = str.Replace("\"", "&#34;");
        return str;
    }

    /// <summary>
    /// 判断是否登陆,登陆返回0，否则返回1
    /// </summary>
    /// <returns></returns>
    public static int IsLogin()
    {
        int result = 0;
        HttpContext hc = HttpContext.Current;
        if (hc.Session["XLHD_UserID"] + "" == "")
            result = 1;
        return result;
    }
}
